package com.rui.common.base;

import com.rui.common.exception.MyException;
import com.rui.common.util.Res;
import com.rui.common.util.SysConst;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * controller基类
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Slf4j
public abstract class BaseController {
    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;

    protected Res res = new Res();

    protected Map<String, Object> mapInit() {
        Map<String, Object> map = new HashMap<>();
        Map<String, String[]> requestMap = request.getParameterMap();
        Set<String> keys = requestMap.keySet();
        for (String key : keys) {
            String modelName = request.getParameter(key);
            if (StringUtils.isNotBlank(modelName)) {
                map.put(key, modelName);
//                log.info("请求参数 : {} = {}", key, modelName);
            }
        }
        if (StringUtils.isNotBlank(request.getParameter(SysConst.PAGE_NUM)) && StringUtils.isNotBlank(request.getParameter(SysConst.PAGE_SIZE))) {
            map.put(SysConst.PAGE_NUM, Integer.parseInt(request.getParameter(SysConst.PAGE_NUM)));
            map.put(SysConst.PAGE_SIZE, Integer.parseInt(request.getParameter(SysConst.PAGE_SIZE)));
        }
        return map;
    }

    protected Map<String, Object> pageInit() {
        Map<String, Object> map = mapInit();
        if (map.containsKey(SysConst.PAGE_NUM) && map.containsKey(SysConst.PAGE_SIZE)) {
            PageHelper.startPage((int) map.get(SysConst.PAGE_NUM), (int) map.get(SysConst.PAGE_SIZE));
        } else {
            throw new MyException("缺少分页参数");
        }
        return map;
    }

    public void down(String fileName, byte[] data) throws IOException {
        response.reset();
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "utf-8"));
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");
        IOUtils.write(data, response.getOutputStream());
    }

}
